package com.westar.core.services;

import com.westar.base.businessUtil.AreaPageUtil;
import com.westar.base.exceptions.LoginException;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.Area;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.WestarHttpUtil;
import com.westar.core.conf.SysConst;
import com.westar.core.dao.AreaDao;
import com.westar.core.dao.LoginDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class AreaService {
    @Autowired
    private AreaDao areaDao;

    /**
     * 初始化区域信息
     */
    public WestarResult initArea(String actCookie) throws IOException {

        //删除表数据
        areaDao.delTable( "area" );
        //获取所有的区域信息
        List<Area> treeAreaList = areaDao.listTreeArea(-1);
        if(null == treeAreaList || treeAreaList.isEmpty()){
            //添加顶部数据
            this.addTopArea();
            //添加区域数据
            this.addSubArea(actCookie);
        }
        return WestarResult.ok( "初始化数据成功！" );


    }

    /**
     * 添加区域信息
     * @param actCookie
     */
    private void addSubArea(String actCookie) throws IOException {
        List<Area> areasList = AreaPageUtil.queryAllArea(actCookie);
        if(null != areasList && !areasList.isEmpty()){
            for (Area area:  areasList) {
                areaDao.add(area);
            }
        }


    }

    /**
     * 添加四川省的数据
     */
    private void addTopArea() {
        Area area = new Area();
        area.setParentAreaId( -1L );
        //上级区域主键
        area.setAreaId(SysConst.AREA_ID);
        //上级区域名字
        area.setAreaName(SysConst.AREA_NAME );
        areaDao.add(area);

    }
}
